/***************************************************
 ** @Desc : This file for 对接充值
 ** @Time : 2019.04.19 10:46
 ** @Author : Joker
 ** @File : api_recharge
 ** @Last Modified by : Joker
 ** @Last Modified time: 2019.04.19 10:46
 ** @Software: GoLand
****************************************************/
package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"recharge/controllers/implement"
	"recharge/models"
	"recharge/sys"
	"recharge/utils"
	"recharge/utils/interface_config"
	"strconv"
	"strings"
)

type ApiRecharge struct {
	beego.Controller
}

var apiRPImpl = implement.ApiRechargePayImpl{}

// 对接充值
// @router /api/recharge/?:params [post]
func (the *ApiRecharge) ApiRecharge() {
	params := models.ApiRechargeRequestParams{}
	params.MerchantNo = the.GetString("MerchantNo")
	params.OrderPrice = the.GetString("OrderPrice")
	params.OutOrderNo = the.GetString("OutOrderNo")
	params.TradeTime = the.GetString("TradeTime")
	params.AccountNo = the.GetString("AccountNo")
	params.AccountName = the.GetString("AccountName")
	params.RecevieBank = the.GetString("RecevieBank")
	params.ApiNotifyUrl = the.GetString("ApiNotifyUrl")
	params.Item = the.GetString("Item")
	params.Sign = the.GetString("Sign")

	//获取客户端ip
	ip := the.Ctx.Input.IP()

	// 校验参数签名
	check, out := apiRPImpl.CheckRequestParams(params, ip)
	if check {

		XFMerchant := merchantFactor.QueryOneMerchantForRecharge()

		record := models.RechargeRecord{}
		record.UserId, _ = strconv.Atoi(params.MerchantNo)
		record.MerchantNo = XFMerchant.MerchantNo

		record.SerialNumber = utils.XF + globalMethod.GetNowTimeV2() + globalMethod.RandomString(10)
		record.ReOrderId = params.OutOrderNo

		record.ReAmount, _ = globalMethod.MoneyYuanToFloat(params.OrderPrice)
		record.ReAccountNo = params.AccountNo
		record.ReAccountName = params.AccountName
		record.ReRecevieBank = params.RecevieBank

		record.NoticeUrl = interface_config.XF_RECHANGE_NOTICE_URL + record.ReOrderId
		record.ApiNoticeUrl = params.ApiNotifyUrl
		record.Item = params.Item
		record.RecordClass = utils.A
		record.CreateTime = params.TradeTime

		// 多通道充值
		switch XFMerchant.ChannelType {
		case utils.XF:
			//先锋
			record.RecordType = utils.XF

			outs, flag := apiXFRecharge(record, XFMerchant)
			if flag < 0 {
				out = outs
			} else {
				out["resultCode"] = "0000"
				out["msg"] = "请求成功"
				out["orderStatus"] = "WAITING_PAYMENT"
			}
		}
	}

	the.Data["json"] = out
	the.ServeJSON()
	the.StopRun()
}

// 对接充值查询
// @router /api/query_recharge/?:params [post]
func (the *ApiRecharge) ApiRechargeQuery() {
	params := models.ApiQueryParams{}
	params.MerchantNo = the.GetString("MerchantNo")
	params.OutTradeNo = the.GetString("OutTradeNo")
	params.Sign = the.GetString("Sign")

	//获取客户端ip
	ip := the.Ctx.Input.IP()

	// 校验参数签名
	check, out := apiRPImpl.CheckRechargeQueryParams(params, ip)
	if check {

		record := rechargeMdl.SelectOneRechargeRecordByOrderId(params.OutTradeNo)
		id, _ := strconv.Atoi(params.MerchantNo)
		info, _ := userMdl.SelectOneUserById(id)

		response := models.ApiQueryResponseBody{}
		response.OutTradeNo = record.ReOrderId
		response.OrderStatus = utils.GetApiOrderStatus()[record.Status]
		response.TradeNo = record.SerialNumber
		response.CompleteTime = record.EditTime

		fee := info.RechargeFee + record.ReAmount*info.RechargeRate*0.001
		response.Amount = globalMethod.MoneyYuanToString(record.ReAmount)
		response.AmountNotFee = globalMethod.MoneyYuanToString(record.ReAmount - fee)
		response.AmountFee = globalMethod.MoneyYuanToString(fee)

		sign := apiRPImpl.GenerateSignV2(response, info.ApiKey)
		response.Sign = sign

		out["resultCode"] = "0000"
		out["msg"] = record.Remark
		out["data"] = response
	}

	the.Data["json"] = out
	the.ServeJSON()
	the.StopRun()
}

// 先锋充值
func apiXFRecharge(record models.RechargeRecord, merchant models.Merchant) (map[string]interface{}, int) {
	out := make(map[string]interface{})

	// 4.0.0版本
	//result, err := xfRecharge(record, merchant.SecretKey)

	// 5.0.0版本
	encode := encrypt.EncodeMd5([]byte(globalMethod.RandomString(32)))
	result, err := xfRechargeV2(record, encode, merchant.SecretKey)
	if err != nil {
		out["resultCode"] = "9998"
		out["msg"] = err
		return out, utils.FAILED_FLAG
	}

	resp := models.XFRechargeResponseBody{}
	err = json.Unmarshal(result, &resp)
	if err != nil {
		sys.LogError("response data format is error:", err)
		out["resultCode"] = "9998"
		out["msg"] = "先锋充值响应数据格式错误"
		return out, utils.FAILED_FLAG
	}

	if strings.Compare("00000", resp.ResCode) != 0 {
		sys.LogDebug("先锋充值错误:", resp)
		out["resultCode"] = "9998"
		out["msg"] = "充值错误: " + resp.ResMessage
		return out, utils.FAILED_FLAG
	}

	record.EditTime = record.CreateTime
	record.Remark = resp.ResMessage

	//状态以异步回调为准
	record.Status = utils.I

	// 添加充值记录
	flag, _ := rechargeMdl.InsertRechargeRecord(record)
	if flag < 0 {
		out["resultCode"] = "9998"
		out["msg"] = "业务异常"
	}
	return out, flag
}
